<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9; IE=10" />
  <title>HERE  Maps API Example: Forwarding to HERE Directions Based on a URL</title>
  <!-- Set up  constants such as APP ID and token -->
  <script type="text/javascript" src="../libs/hereAppIdAndToken.js"></script>
  <!-- Bootstrap jQuery Library -->
  <script type="text/javascript" src="../libs/jQl.min.js"></script>
  <!-- Asynchronously  the  HERE Maps API for JavaScript -->
  <script  type="text/javascript" src="../libs/hereAsyncLoader.js"
    id="HereMapsLoaderScript" data-params="maps" data-callback="findWaypoints">
  </script>
  <link rel="icon" href="http://here.com/favicon.ico">
  <!--<link href="http://developer.here.com/html/css/main.css" rel="stylesheet" />-->
</head>
<body style="">
  <h1>Forwarding to HERE Maps  directions Based on  a URL</h1>
  <p style="width:540px;"  >This uses geocoding , to forward a request to HERE Maps.
  </p>


  <div id="ticker" style="height:  2.0em; font-size: 2em; color: blue;"></div>
  <div id="uiContainer">
      Click on a link  to pre-open  the  directions renderer:<br>

      <ul>
        <li>
          <a href="index.html?addr1=Avenida  Dona Ana Costa Santos Brazil&amp;addr2=Avenida Paulista  S%C3%A3o Paulo Brazil">
          Street Level Routing</a> - Avenida Dona  Ana  Costa, Santos to Avenida Paulista, S&atilde;o Paulo
        </li>
        <li><a href="index.html?addr1=Sacramento California&amp;addr2=San  Francisco California">
          City and State Routing.</a>  - Sacramento, CA to  San  Francisco, CA
        </li>
        <li><a href="index.html?addr1=Madrid,Spain&amp;addr2=Marsella,France&amp;ml=es">City to City Routing</a> - Madrid to Marseilles
        </li>
        <li><a href="index.html?addr1=%E5%8C%97%E4%BA%AC&amp;addr2=%E4%B8%8A%E6%B5%B7">
          City to  City Routing.</a> - &#21271;&#20140; (Beijing) to &#19978;&#28023; (Shanghai)
        </li>
        <li><a href="index.html?addr1=Scotland Yard,London,UK&amp;addr2=221b  Baker Street,London,UK&amp;addr3=Bow+Street,WC2,London,UK&amp;sb=m">
            Routing  with intermediate waypoints</a>  - Scotland Yard  to Bow Street via 221b Baker Street  (distances in miles)
        </li>
        <li><a href="index.html?lat1=-33.859972&amp;long1=151.212111&amp;lat2=-33.859972&amp;long2=151.211111&amp;lat3=-33.859972&amp;long3=151.19">
          Routing via geocoordinates</a> - around  Sydney harbour.
        </li>
      </ul>
    </div>

<script id="example-code" data-categories="routing" type="text/javascript" >
//<![CDATA[

var addresses =  [],
  managersCount = 0,
  managersFinished = 0,
  geoCodedWaypoints = [],
  expectedWaypoints = 0;

function getParameterByName(name) {
  name = name.replace(/[\[]/,  '\\\[').replace(/[\]]/, '\\\]');
  var regex =  new RegExp('[\\?&]'  + name + '=([^&#]*)'),
    results  = regex.exec(location.search);
  return results === null ? '' :
      decodeURIComponent(results[1].replace(/\+/g, ' '));
}



function buildURLfromWaypoints() {
  var url = 'http://maps.nokia.com/services/directions?',
    len =  geoCodedWaypoints.length,
    i;

  for (i = 0; i < len; i++) {
    // Check than none of the waypoints are null.
    if (geoCodedWaypoints[i] === null) {
      $('#ticker').text('Geocoding Failed');
      break;
    }
  }
  for (i = 0; i < len; i++) {
    if (i > 0) {
      url = url + '&';
    }
    url = url + 'x' + i + '=' + geoCodedWaypoints[i].latitude +
      '&y' + i + '=' +  geoCodedWaypoints[i].longitude;


    if (addresses.length > i && addresses[i] !== null) {
      url = url + '&n' + i + '=' + addresses[i];
    } else if (i > 0 && i < geoCodedWaypoints.length - 1) {
      url = url + '&n' + i + '=.';
    }
  }

  url = url + '&route_type=fastest&transport_mode=car';
  window.location = encodeURI(url);

}

// Geocoding Manager function -
// we will use the same  state observer function  for  all  managers.
// This  allows use to make concurrent requests.
//  Once all addresses have  been geocoded. We can start  the  route calculation.
function SearchManager($index) {
  var that = this;
  that.index  = $index;
  that.onSearchComplete = function (data,  requestStatus) {
    // If the search has finished we can process the results
    if (requestStatus === 'OK') {
      geoCodedWaypoints[that.index] = data.location.position;
      //increment the counter to notify another  manager has finished
      managersFinished++;
    } else if (requestStatus === 'ERROR') {
      // we'll also increment in case of an error
      managersFinished++;
    }

    // if all managers are finished, we  call the final function
    if (managersFinished === managersCount) {
      buildURLfromWaypoints(geoCodedWaypoints);
    }
  };
}

function findWaypoints() {
  // Loop  thorugh  the  first 10 parameters  and  see  if the are addresses or  geo-coordinates.
  // Add them  to the appropriate bucket.
  var i,
    lat,
    lng,
    addr;
  for (i = 0;  i <  10;  i += 1) {
    lat = getParameterByName('lat' + i);
    lng = getParameterByName('long'  + i);
    addr = getParameterByName('addr' + i);
    if (addr !== '') {
      addresses.push(getParameterByName('addr' + i));
      expectedWaypoints++;
    } else if (lat !== '' &&  lng  !== '') {
      geoCodedWaypoints.push(new nokia.maps.geo.Coordinate(
        parseFloat(lat, 10),
        parseFloat(lng, 10)
      ));
      expectedWaypoints++;
    }
  }


  // Concurrent search Manager set up.
  // Assume we have at least one address to geocode.
  if (addresses.length >  1) {
    // iterate over  all  addresses, create a  manager  for  each of  them,
    // add the observer  and  call the geocode method.
    // Once  all  managers have completed
    // the calculateRouteFromKnownWaypoints() function will  be run.
    $('#ticker').text('Geo-coding Addresses');
    managersCount = addresses.length;
    i = addresses.length;
    while (i--) {
      nokia.places.search.manager.geoCode({
        searchTerm : addresses[i],
        onComplete:   new SearchManager(i).onSearchComplete
      });
    }
  } else if (geoCodedWaypoints.length  > 1) {

    buildURLfromWaypoints(geoCodedWaypoints);
  } else {
    // If we have neither addresses  nor  geolocations, we can't define a  route.
    $('#ticker').text('No addresses  found.');
  }
}
//]]>
</script>
</body>
</html>